package com.Guigu.service.impl;

import com.Guigu.domain.LoginUser;
import com.Guigu.domain.User;
import com.Guigu.mapper.MenuMapper;
import com.Guigu.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

//    private final UserMapper userMapper;
    @Autowired
    private  UserMapper userMapper;
//    private final MenuMapper menuMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user=userMapper.selectOne(queryWrapper);
        //如果没有查询到对象抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名户密码错误！");
        }
        //把数据权限信息封装成UserDetails
        //List<String>list=new ArrayList<>(Arrays.asList("test","admin"));
        //把数据封装成UserDetail返回
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user,list);
    }
}
